package com.jqb.dom;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.junit.Test;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;



public class Dom {
	@Test
	public void testDmo() throws Exception{
		domParse();
		domCreate();
	}

	public static void domParse() throws ParserConfigurationException,
			SAXException, IOException {
		/*--->parse<---*/
		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = builder.parse(new File("src/test/resources/users.xml"));
		Element root = doc.getDocumentElement();
		NodeList names = root.getElementsByTagName("name");
		for(int i=0;i<names.getLength();i++){
			System.out.println("name="+names.item(i).getFirstChild().getNodeValue());
		}
		NodeList user = root.getElementsByTagName("user");
		for(int i=0;i<user.getLength();i++){
			NamedNodeMap id = user.item(i).getAttributes();
			System.out.println(id.item(0).getNodeName()+"="+id.item(0).getNodeValue());
		}
	}
	
	public static void domCreate() throws ParserConfigurationException,
			TransformerFactoryConfigurationError,
			TransformerConfigurationException, TransformerException {
		/*--->create<---*/
		Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		/*创建各个节点*/
		Element users = doc.createElement("users");
		Element user = doc.createElement("user");
		Element name = doc.createElement("name");
		/*创建属性*/
		Attr id = doc.createAttribute("id");
		/*创建文本节点*/
		name.appendChild(doc.createTextNode("admin1000"));
		/*给属性赋值*/
		id.setNodeValue("1000");
		/*连接节点*/
		user.appendChild(name);
		user.setAttributeNode(id);
		users.appendChild(user);
		doc.appendChild(users);
		/*包装DOM*/
		DOMSource source = new DOMSource(doc);
		PrintWriter out = new PrintWriter(System.out);
		/*包装输出流*/
		StreamResult result = new StreamResult(out);
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		/*将DOM转换为输出流*/
		transformer.transform(source, result);
	}
}
